// 提交链接 https://leetcode.cn/problems/minimum-size-subarray-sum/submissions/558817826/
// 209. 长度最小的子数组
// 完成日期： 2024.8.30
// c++ 使用二分枚举长度，双指针验证


class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int head = 0, tail = nums.size() + 1;
        while (head < tail)
        {
            int mid = (head + tail) / 2;
            int num = 0;
            for (int i = 0; i < mid; i++) num += nums[i];
            if (num >= target)
            {
                tail = mid; continue;
            }
            int l = 1, r = mid;
            int flag = 1;
            while (r < nums.size())
            {
                num += nums[r];
                num -= nums[l - 1];
                if (num >= target)
                {
                    tail = mid; flag = 0; break;
                }
                l += 1;
                r += 1;
            }
            if (flag) head = mid + 1;
        }
        return head > nums.size() ? 0 : head;
    }
};